package simpleZKlock;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @program: hadoop
 * @description: 分布式锁
 * @author: Qiang.Ye
 * @create: 2019-06-01 19:35
 **/
public class TestDistributedLock {

    private static int  count = 10;


    private static  void  printCountNum(){
        System.out.println("====="+Thread.currentThread().getName()+"=========");
        System.out.println("当前值："+count);
        count--;
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("======="+Thread.currentThread().getName()+"========");

    }

    public static void main(String[] args) {

//        ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 10, 1000);
        //客户端重试策略    参数值：【每次等待的时间，重试次数】
        ExponentialBackoffRetry retry =
                new ExponentialBackoffRetry(1000, 10);
        //定义一个ZK客户端
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("bigdata111:2181").retryPolicy(retry).build();
        client.start();

        InterProcessMutex mylock = new InterProcessMutex(client, "/mylock");

        for(int i=0;i<10;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        mylock.acquire();
                        printCountNum();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {
                        try {
                            mylock.release();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                }
            }).start();

        }



    }





}
